import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

import '../../services/ScreenAdapter.dart';
import '../../config/Config.dart';
import '../../services/UserInfo.dart';
import '../../services/SignServices.dart';
import '../../services/EventBus.dart';
import '../../services/SignServices.dart';

// 地址列表页面
class AddressListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => AddressListState();
}

class AddressListState extends State {
  var defaultAddressId;
  List addressInfo = [];
  String loadingMsg = '正在加载中...';
  bool isLoading = true;
  var actionEvent;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('收货地址列表')),
      body: Stack(
        children: [
          isLoading
              ? Center(
                  child: Text('$loadingMsg'),
                )
              : Container(
                  child: addressInfo.length > 0
                      ? ListView.builder(
                          itemCount: addressInfo.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Column(
                              children: [
                                ListTile(
                                  leading: defaultAddressId ==
                                          addressInfo[index]['_id']
                                      ? Icon(Icons.check, color: Colors.red)
                                      : null,
                                  title: Column(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                          '${addressInfo[index]['name']}  ${addressInfo[index]['phone']}',
                                          style: TextStyle(fontSize: 14)),
                                      SizedBox(height: 10),
                                      Text('${addressInfo[index]['address']}',
                                          style: TextStyle(fontSize: 14))
                                    ],
                                  ),
                                  trailing: InkWell(
                                    child: Container(
                                      width: ScreenAdapter.width(80),
                                      height: double.infinity,
                                      child:
                                          Icon(Icons.edit, color: Colors.blue),
                                    ),
                                    onLongPress: () {
                                      // 跳转到编辑页面
                                      Navigator.pushNamed(
                                          context, '/addressEdit', arguments: {
                                        "addressInfo": addressInfo[index]
                                      });
                                    },
                                  ),
                                  onTap: () {
                                    _changeDefaultAddress(addressInfo[index]);
                                  },
                                  onLongPress: () {
                                    showDialog(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return _showAlertDialog(addressInfo[index]);
                                        });
                                  },
                                ),
                                Divider()
                              ],
                            );
                          },
                        )
                      : Center(
                          child: Text('$loadingMsg'),
                        ),
                ),
          Positioned(
              bottom: 0,
              child: Container(
                width: ScreenAdapter.width(750),
                height: ScreenAdapter.height(90),
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.red,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [Icon(Icons.add), Text('新增收货地址')],
                  ),
                  onPressed: () {
                    Navigator.pushNamed(context, '/addressAdd');
                  },
                ),
              ))
        ],
      ),
    );
  }

  initState() {
    super.initState();

    // 获取用户全部地址
    _getAllAddress();

    //监听广播，刷新页面
    this.actionEvent = eventBus.on<AddressListUploadEvent>().listen((event) {
      // 重新刷新，获取用户全部地址
      _getAllAddress();

      eventBus.fire(new CheckOutAddressUploadEvent('CheckOut页面重新刷新'));
    });

    // 获取用户默认收货地址
    _getOneAddress();
  }



  @override
  dispose(){
    super.dispose();
    actionEvent.cancel();
  }

  // 长按地址，弹出弹框，是否删除地址
  _showAlertDialog(addressInfo) {
    return AlertDialog(
      content: Text('您确定要删除这条地址么？'),
      actions: [
        FlatButton(
          child: Text('取消', style: TextStyle(color: Colors.black)),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
        FlatButton(
          child: Text('确定', style: TextStyle(color: Colors.black)),
          onPressed: (){_deleteAddress(addressInfo);},
        ),
      ],
    );
  }

  // 点击确定，删除地址
  _deleteAddress(addressInfo) async {
    var userInfo = await UserInfoServices.getUserInfo();

    Map tempJson = {
      "uid": addressInfo['uid'],
      "id": addressInfo['_id'],
      "salt": userInfo[0]['salt'],
    };

    var sign = SignServices.getSign(tempJson);

    var api = Config.domain + 'api/deleteAddress';
    var response = await Dio().post(api, data: {
      "uid": addressInfo['uid'],
      "id": addressInfo['_id'],
      "sign": sign,
    });

    var res = response.data;
    if(res['success']){
      // 弹框提示
      Fluttertoast.showToast(
        msg: "该地址删除成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
      eventBus.fire(new AddressListUploadEvent('AddressList页面重新刷新'));
      Navigator.of(context).pop();
    }

  }

  // 获取用户默认收货地址
  _getOneAddress() async {
    var userInfo = await UserInfoServices.getUserInfo();

    var tempJson = {
      "uid": userInfo[0]['_id'],
      "salt": userInfo[0]['salt'],
    };

    var sign = SignServices.getSign(tempJson);
    var api = Config.domain + 'api/oneAddressList';

    var response = await Dio().get(api, queryParameters: {
      "uid": userInfo[0]['_id'],
      "sign": sign,
    });

    var res = response.data;
    if (res['success']) {
      this.setState(() {
        if (res['result'].length > 0){
          defaultAddressId = res['result'][0]['_id'];
        }else {
          defaultAddressId = null;
        }

      });
    }
  }

  // 修改默认收货地址
  _changeDefaultAddress(addressInfo) async {
    var userInfo = await UserInfoServices.getUserInfo();
    var tempJson = {
      "uid": addressInfo['uid'],
      "id": addressInfo['_id'],
      "salt": userInfo[0]['salt'],
    };

    var sign = SignServices.getSign(tempJson);
    var api = Config.domain + 'api/changeDefaultAddress';

    var response = await Dio().post(api, data: {
      "uid": addressInfo['uid'],
      "id": addressInfo['_id'],
      "sign": sign
    });

    var res = response.data;
    if (res['success']) {
      eventBus.fire(new CheckOutAddressUploadEvent('CheckOut页面重新刷新'));

      // 弹框提示
      Fluttertoast.showToast(
        msg: "设置默认地址成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );

      this.setState(() {
        defaultAddressId = addressInfo['_id'];
      });
    }
  }

  // 获取用户全部地址
  _getAllAddress() async {
    this.setState(() {
      addressInfo = [];
      loadingMsg = '正在加载中...';
      isLoading = true;
    });

    List userInfo = await UserInfoServices.getUserInfo();

    var tempJson = {"uid": userInfo[0]['_id'], "salt": userInfo[0]['salt']};

    var sign = SignServices.getSign(tempJson);

    var api = Config.domain + 'api/addressList';
    var response = await Dio()
        .get(api, queryParameters: {"uid": userInfo[0]['_id'], "sign": sign});

    var res = response.data;

    if (res['success']) {
      this.setState(() {
        addressInfo = res['result'];
        if (addressInfo.length == 0) {
          loadingMsg = '没有地址数据...';
          isLoading = false;
        } else {
          isLoading = false;
        }
      });
    }
  }
}
